import os

import yaml
from selenium import webdriver

# find/click等浏览器操作
from selenium.common import NoSuchElementException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from test_pytest.Utils.log_util import logger


class BaseDriver:
    def __init__(self, driver: WebDriver = None):
        # 处理driver被反复初始化
        if driver is None:
            opt = webdriver.ChromeOptions()
            self._driver = webdriver.Chrome()
            # 打开网页
            self._driver.get("https://work.weixin.qq.com/wework_admin/frame#index")
            # 获取当前路径
            print(os.getcwd())
            # 读取cookie.yaml文件
            with open("cookie.yaml", encoding="utf-8") as f:
                cookies = yaml.safe_load(f)
            # 遍历cookies追加到driver
            for cookie in cookies:
                self._driver.add_cookie(cookie)
            # 设置隐式等待
            self._driver.implicitly_wait(10)
            self._driver.get("https://work.weixin.qq.com/wework_admin/frame#index")
        else:
            # 如果不是none就用传递进来的driver
            logger.info("用传递进来的driver")
            self._driver = driver

    def find(self, by, value=None):
        # 判断是否是一个元组，如果是解元组传递
        if isinstance(by, tuple):
            return self._driver.find_element(*by)
        else:
            return self._driver.find_element(by, value)

    def find_content(self, by, value, content: str):
        result = self._driver.find_element(by, value).send_keys(content)
        return result

    def finds(self, by, value=None):
        if isinstance(by, tuple):
            return self._driver.find_elements(*by)
        else:
            return self._driver.find_elements(by, value)

    def find_and_click(self, by, value):
        result = self._driver.find_element(by, value).click()
        return result

    def wait_time(self, time, condition: tuple):
        # 封装显示等待
        wait = WebDriverWait(self._driver, time).until(expected_conditions.visibility_of_element_located(condition))
        return wait

    def close_browser(self):
        self._driver.quit()

    def wait_elements(self, click_element, wait_element, click_num=5):
        # 计数器
        num = 1
        while True:
            logger.info(f"第{num}次点击")
            # find_element:找不到会直接抛出异常，后面代码不在执行。
            # find_elements:找不到会返回一个空的列表。找到多个会只返回第一个元素
            ele = self.finds(wait_element)
            # 如果找到姓名输入框，证明进入添加成员的页面，跳出循环，没有找到就一直点击
            if num >= click_num:
                raise NoSuchElementException
            if len(ele) <= 0:
                add_num = self.find(click_element)
                add_num.click()
                num += 1
            else:
                break






